package com.leyou.service.Impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.service.UploadService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadServiceImpl implements UploadService {

    //定义文件的校验规则
    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif", "image/png");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    FastFileStorageClient storageClient;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {

        try {
            //校验文件类型是否合法
            String contentType = file.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
                //文件不合法
                LOGGER.info("文件类型不合法", file.getOriginalFilename());
                return null;
            }

            //检验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                LOGGER.info("文件内容不合法", file.getOriginalFilename());
                return null;
            }

                /*//保存文件
                file.transferTo(new File("E:\\images\\",file.getOriginalFilename()));

                //返回保存文件的url
                return "http://image.leyou.com/"+file.getOriginalFilename();
            } catch (IOException e) {
                LOGGER.info("服务器内部错误：{}", file.getOriginalFilename());
                e.printStackTrace();
            }
            return null;*/

            //将图片上传到fastDFS
            // 获取文件后缀名
            String last = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

            //上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), last, null);

            //返回完整路径
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
